package com.yang.qgg_demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.qgg_demo.common.R;
import com.yang.qgg_demo.entity.Files;
import com.yang.qgg_demo.mapper.FileMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Autowired
    private FileMapper fileMapper;

    /**
     * 文件上传接口
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String uploadFile(@RequestParam MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String type = FileUtil.extName(fileName);
        long size = file.getSize();
        //先存储到磁盘
        File uploadParentFile = new File(fileUploadPath );
        //判断配置的文件目录是否存在，不存在则产生一个新的文件目录
        if (!uploadParentFile.exists()) {
            uploadParentFile.mkdirs();
        }
        //定义一个唯一文件标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUuid = uuid + StrUtil.DOT + type;

        File uploadFile = new File(fileUploadPath + fileUuid);
        //把获取的文件存储到磁盘目录
        file.transferTo(uploadFile);
        String url = "http://localhost:9090/file/download?fileUuid=" + fileUuid;

        //存储数据库
        Files files = new Files();
        files.setName(fileName);
        files.setType(type);
        files.setSize(size);
        files.setUrl(url);
        fileMapper.insert(files);
        return url;
    }

    /**
     *分页查询接口
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Files>> findPage(@RequestParam Integer pageNum,
                                   @RequestParam Integer pageSize){
//                                   @RequestParam(defaultValue = "") String name) {

        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", false);
//        if (!"".equals(name)) {
//            queryWrapper.like("name", name);
//        }
        return R.success(fileMapper.selectPage(new Page<>(pageNum,pageSize),queryWrapper));
    }

    @GetMapping("/{id}")
    public R findOne(@PathVariable Integer id) {
        Files files = fileMapper.selectById(id);
        files.setIs_delete(true);
        return R.success(fileMapper.updateById(files));
    }

    /**
     * 下载接口
     */
    @GetMapping("/download")
    public void download(String fileUuid, HttpServletResponse response){

        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(fileUploadPath + fileUuid));

            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}